package com.lagou.work5.server;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;

public class Server {
    private static final int MAX_SOCKET_NUM = 10;
    public static int socketNum =0;
    public static Socket[] users = new Socket[MAX_SOCKET_NUM];
    public static void main(String[] args) {

        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            // 初始化本地资源目录
            File userLocalStorage = new File("/Users/dingxiaowei/Downloads/server");
            if(!userLocalStorage.exists()){
                userLocalStorage.mkdirs();
            }
            System.out.println("服务器资源目录已初始化成功");
            System.out.println("服务器已启动，等待连接中......");

            // 固定用户连接个数为10个
            while (socketNum < MAX_SOCKET_NUM) {
                users[socketNum] = serverSocket.accept();
                // 连接成功，获取用户名
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(users[socketNum].getInputStream()));
                // 首次连接时，读取一次
                String userName = bufferedReader.readLine();
                // 输出用户连接成功消息
                System.out.println(userName+",上线！");

                // 启动一个线程，专门处理该用户的消息
                Thread serverThread = new Thread(new ServerReceiver(userName,socketNum));
                serverThread.start();
                socketNum++;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
